package com.jeek.jdbc.myCode.homeWork;

import com.jeek.jdbc.myCode.homeWork.entity.Admin;
import com.jeek.jdbc.myCode.homeWork.entity.Stus;
import com.jeek.jdbc.myCode.homeWork.preparestatement.AdminDAO;
import com.jeek.jdbc.myCode.homeWork.preparestatement.StudentDao;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.sql.SQLException;

public class Main {
    // 直接使用DAO层操作数据库
    private static final StudentDao studentDAO = new StudentDao();
    private static final AdminDAO adminDAO = new AdminDAO();
    private static final Scanner scanner = new Scanner(System.in);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) {
        // 登录验证
        if (login()) {
            System.out.println("登录成功！");
            // 主界面循环
            while (true) {
                showMainMenu();
                int choice = scanner.nextInt();
                scanner.nextLine();
                handleChoice(choice);
            }
        } else {
            System.out.println("用户名或密码错误，登录失败！");
        }
        scanner.close();
    }

    // 登录方法（直接调用AdminDAO查询数据库）
    private static boolean login() {
        System.out.print("请输入管理员用户名：");
        String username = scanner.nextLine();
        System.out.print("请输入管理员密码：");
        String password = scanner.nextLine();

        try {
            // 从数据库查询匹配的管理员
            Admin admin = adminDAO.queryAdmin(username, password);
            return admin != null;
        } catch (SQLException e) {
            System.out.println("登录失败 " + e.getMessage());
            return false;
        }
    }

    // 展示主菜单
    private static void showMainMenu() {
        System.out.println("\n===== 学生管理系统 =====");
        System.out.println("1. 统计学生人数");
        System.out.println("2. 查看学生名单");
        System.out.println("3. 按学号查询学生姓名");
        System.out.println("4. 按姓名查询学生信息");
        System.out.println("5. 修改学生出生日期");
        System.out.println("6. 删除学生记录");
        System.out.println("0. 退出系统");
        System.out.print("请选择操作（输入数字）：");
    }

    // 处理用户选择（直接调用StudentDAO）
    private static void handleChoice(int choice) {
        try {
            switch (choice) {
                case 1: // 统计学生人数
                    int count = studentDAO.countAllStudents();
                    System.out.println("当前系统学生总人数：" + count);
                    break;

                case 2: // 查看所有学生名单
                    List<Stus> allStudents = studentDAO.selectAllStudents();
                    if (allStudents.isEmpty()) {
                        System.out.println("系统中暂无学生信息！");
                    } else {
                        printStudentTable(allStudents);
                    }
                    break;

                case 3: // 按学号查询姓名和年级
                    System.out.print("请输入要查询的学生学号（如S0001）：");
                    String queryId = scanner.nextLine();
                    // 简单校验学号格式
                    if (!queryId.matches("^S\\d+$")) {
                        System.out.println("学号格式错误！需以S开头，后接数字（如S0001）");
                        break;
                    }
                    Stus studentById = studentDAO.selectOneById(queryId);
                    if (studentById != null) {
                        System.out.println("查询结果：");
                        System.out.println("学号：" + queryId + "，姓名：" + studentById.getName() + "，年级：" + studentById.getGrade());
                    } else {
                        System.out.println("未查询到学号为" + queryId + "的学生！");
                    }
                    break;

               // 在 Main.java 的 handleChoice 方法中
case 4:
    System.out.print("请输入要查询的学生姓名（支持模糊查询）：");
    String queryName = scanner.nextLine();
    if (queryName.trim().isEmpty()) {
        System.out.println("姓名不能为空！");
        break;
    }

    // 如果方法返回单个对象
    Stus student = studentDAO.selectOneByName(queryName);
    List<Stus> studentsByName;
    if (student != null) {
        studentsByName = new ArrayList<>();
        studentsByName.add(student);
    } else {
        studentsByName = new ArrayList<>();
    }

    if (studentsByName.isEmpty()) {
        System.out.println("未查询到姓名含“" + queryName + "”的学生！");
    } else {
        System.out.println("查询到" + studentsByName.size() + "条结果：");
        printStudentTable(studentsByName);
    }
    break;


                case 5: // 修改学生出生日期
                    System.out.print("请输入要修改的学生学号：");
                    String updateId = scanner.nextLine();
                    // 先校验学号是否存在
                    Stus checkUpdate = studentDAO.selectOneById(updateId);
                    if (checkUpdate == null) {
                        System.out.println("学号" + updateId + "不存在！");
                        break;
                    }
                    System.out.print("请输入新的出生日期（格式：yyyy-MM-dd）：");
                    String newBirthStr = scanner.nextLine();
                    Date newBirthDate;
                    try {
                        newBirthDate = (Date) sdf.parse(newBirthStr);
                        // 校验日期合理性（不能晚于当前时间）
                        /*if (newBirthDate.after( new Date())) {
                            System.out.println("出生日期不能晚于当前时间！");
                            break;
                        }*/
                    } catch (ParseException e) {
                        System.out.println("日期格式错误！请按yyyy-MM-dd格式输入（如1998-03-03）");
                        break;
                    }
                    boolean updateSuccess = studentDAO.updateBirthday(updateId, newBirthDate);
                    if (updateSuccess) {
                        System.out.println("学号" + updateId + "的出生日期修改成功！");
                    } else {
                        System.out.println("修改失败，请重试！");
                    }
                    break;

                case 6: // 删除学生记录
                    System.out.print("请输入要删除的学生学号：");
                    String deleteId = scanner.nextLine();
                    // 先校验学号是否存在
                    Stus checkDelete = studentDAO.selectOneById(deleteId);
                    if (checkDelete == null) {
                        System.out.println("学号" + deleteId + "不存在！");
                        break;
                    }
                    // 确认删除
                    System.out.print("确认删除学号" + deleteId + "（姓名：" + checkDelete.getName() + "）的信息吗？(Y/N)：");
                    String confirm = scanner.nextLine();
                    if ("Y".equalsIgnoreCase(confirm)) {
                        boolean deleteSuccess = studentDAO.deleteStudent(deleteId);
                        if (deleteSuccess) {
                            System.out.println("学号" + deleteId + "的信息已成功删除！");
                        } else {
                            System.out.println("删除失败，请重试！");
                        }
                    } else {
                        System.out.println("已取消删除操作！");
                    }
                    break;

                case 0: // 退出系统
                    System.out.println("系统已退出，感谢使用！");
                    System.exit(0);
                    break;

                default:
                    System.out.println("无效操作！请输入0-6之间的数字");
            }
        } catch (SQLException e) {
            System.out.println("操作失败：数据库错误 - " + e.getMessage());
        }
    }

    // 打印学生信息表格
    private static void printStudentTable(List<Stus> students) {
        // 表头
        System.out.printf("%-10s %-8s %-6s %-6s %-15s %-20s %-12s%n",
                "学号", "姓名", "性别", "年级", "电话", "邮箱", "出生日期");
        System.out.println("------------------------------------------------------------------------------------------------");
        // 表内容
        for (Stus s : students) {
            System.out.printf("%-10s %-8s %-6s %-6s %-15s %-20s %-12s%n",
                    s.getId(),
                    s.getName(),
                    s.getGender(),
                    s.getGrade(),
                    s.getPhone(),
                    s.getEmail(),
                    sdf.format(s.getBirthday()));
        }
    }
}